<?php
if( !defined('IN_INDEX') )
{
	printError("ACCESS DENIED", "This page is hidden.");
	exit;
}

include './inc/functions_blog.php';

$com['comment'] = str_replace("'", "\'", $_POST['comment']);
$com['owner'] = intval($_POST['owner_id']);
$com['rating'] = -1;
$post_type = 'training';
$post_id = intval($_POST['tid']);

$sql = "INSERT INTO comments SET ".
"post_id='" . $post_id . "', ".
"post_type='" . $post_type . "', ".
"user_id='" . $USER->getId() . "', ".
"comment_text='" . $com['comment'] . "', ".
"comment_date='" . time() . "', ".
"comment_rating='" . $com['rating'] . "', ".
"comment_owner='" . $com['owner'] . "'";

if(!$result = $db->sql_query($sql))
{
	printerror("SQL ERROR", mysql_error($sql) ."<br />" . mysql_errno($sql));
}
// Add +1 to user_posts
$sql2 = "UPDATE users SET user_posts = user_posts+1 WHERE user_id =" . $USER->getId() . "";
if(!$result2 = $db->sql_query($sql2))
{
	printError("SQL ERROR", mysql_error($sql2));
}
else
{
if(!isset($USER_PROFILE))
{
	$USER_PROFILE = new User('id', $com['owner']);
}

if($USER_PROFILE->getMsgFromComments() == 1 && $USER_PROFILE->getId() != 0 && $USER_PROFILE->getId() != 1 && $USER_PROFILE->getId() != $USER->getId())
{
	switch($post_type)
	{
		case 'training':
			$pm_id = $USER->getId();
			$pm_subject = translate('newcommentonyourblog') ." <b>" . getTrainingTitle($post_id) . "</b>";
			$pm_body = formatComment($com['comment']) . "<br /><br />
			<a href=\"index.php?action=profile&sub=show&tid=" . $post_id . "\"> " .htmlentities( translate('clicktogotopost') ). " </a>";
			sendPM($USER_PROFILE->getId(), $pm_id, $pm_subject, $pm_body, 0);
			hook_send_email($USER_PROFILE->getId(), $pm_id, $pm_subject, $pm_body, 0);
			break;
		default:
			break;
	}
}

//Send PM to other commenters
$user_commented = checkUserCommented($USER->getId(), $post_id);
foreach($user_commented as $val)
{
	if(checkMsgFromcomments($val['user_id']) == 1 && $val['user_id'] != $USER_PROFILE->getId())
	{
		$pm_id = $USER->getId();
		$pm_subject = translate('alsocommentedontheblog') ." <b>" . getTrainingTitle($post_id) . "</b>";
		$pm_body = formatComment($com['comment']) . "<br /><br /><a href=\"index.php?action=profile&sub=show&tid=" . $post_id . "\"> " .htmlentities( translate('clicktogotopost') ). " </a>";
		sendPM($val['user_id'], $pm_id, $pm_subject, $pm_body, 0);
		hook_send_email($val['user_id'], $pm_id, $pm_subject, $pm_body, 0);
	}
}
}

echo 'ok';
exit();